/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package zeroticket;

import java.util.List;
import javax.smartcardio.CardException;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.TerminalFactory;

/**
 *
 * @author giovannirojas
 */
public class ReaderUtils {

    
    public static CardTerminal getTerminalByName(String terminalName) throws NFCException {
        try {
            TerminalFactory terminalFactory = TerminalFactory.getDefault();
            List<CardTerminal> terminals = terminalFactory.terminals().list();
            for (CardTerminal terminal : terminals) {
                if (terminal.getName().contains(terminalName)) {
                    return terminal;
                }
            }
        } catch (CardException e) {
            throw new NFCException("Error : "+e);
        }
        throw new  NFCException("No card terminal found, expected: [" + terminalName + "], available: [" + getAvailableTerminals() + "]");
    }

    private static String getAvailableTerminals() {
        StringBuilder sb = new StringBuilder();
        TerminalFactory terminalFactory = TerminalFactory.getDefault();
        try {
            List<CardTerminal> terminals = terminalFactory.terminals().list();
            for (CardTerminal terminal : terminals) {
                if (sb.length() != 0) {
                    sb.append(", ");
                }
                sb.append(terminal.getName());
            }
        } catch (CardException e) {
        }
        return sb.toString();
    }
}
